var app = getApp();
import {
  api,
  util, 
  dialog,
  clickIncrement,
  clearIncrement, 
  forms,
  storage
} from '../../../../js/util'
import {
  router,
  pagesInfo
} from '../../../../js/router'
import {
  fastorder,
  order,
  cart
} from "../../../../js/modules/order.js"
import {
  detail,
  mall,
  list,
  scant
} from "../../../../js/modules/mall.js";
import {
  activities
} from '../../../../js/modules/market';
import {
  area,config
} from '../../../../js/modules/gloab';
import {
  GoodsNumCache
} from '../../../../js/modules/propertycache.js'
import {
  upload
} from '../../../../js/modules/material.js'
import authorize from '../../../../js/modules/authorize'
import { theme } from '../../../../js/modules/theme'
import BasePage from '../../../../js/common/base-page'
import { getStorageSync, hideTabbar, setStorageSync } from '../../../../js/compatible';
BasePage({
  pageKey: "category",
  validateLogin: app.dns.fkId != app.dns.proprietorId,
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    allTabList:['目录', '收藏', '常购', '复购', '套餐', '拍照'],
    tablist: [],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 10,
    slidewidth: 0,
    lists: [{
        activeIndex: 0,
        pageKey: "category",
        time:null,
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: ""
        }
      },
      {
        activeIndex: 1,
        pageKey: "favorite",
        time: null,
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: ""
        }
      },
      {
        activeIndex: 2,
        pageKey: "offenBuy",
        time: null,
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          sortDirect: ""
        }
      },
      {
        activeIndex: 3,
        pageKey: "repurchase",
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          sortDirect: "desc"
        }
      },
      {
        activeIndex: 4,
        pageKey: "scan",
      },
      {
        activeIndex: 5,
        pageKey: "takePhoto",
      }
    ],
    choosePanicbuy: [],
    chooseGoodsArray: [],
    chooseGoodsSpec: [],
    chooseGoodsUnits: [],
    code: "",
    isPanic: false,
    isScanty: false,
    quantityDigits: 0,
    priceDigits:2,
    decimalDigits:2,
    spectStyle:0,
    scantyProduct: [],
    is_search:false,
    tabKey: "product_" + app.dns.proprietorId,
    isAginBuying:false,
    isLogin: authorize.isLogin(),
    photolist:[],
    virtualImageList:[],
    loopCount:0,
    visitTimer:null,
    isIphoneX:app.globalData.isIphoneX,
    mainColor:'',//主题色
    Currency:'',//货币符号
    NoLoginShowPrice:false,//未登录状态显示价格
    showRetailPrice:false,//登录状态下显示市场价
    isLogin:true,//判断是否登录
    CartName:'',//
    FieldDisplayName:[],
    ClassDisplayField:{},
    listState:true,
    tabindex:-1,
    cids:0,
    listType:true,
    IsGoodsTrading:false,
    widgets:[],
    GoodsUnitDisplayMode:0,
    ShowVendorName:false,
    FrontShowStockDetail:false,
    AppQuickTemplateConfig: {}, // 快速下单的目录样式
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.initTabBar();
    this.productlist = this.selectComponent("#productlist");
    this.fasterComponent = this.selectComponent("#fasterComponent");
    this.outofstock = this.selectComponent("#outofstock");
    this.stockdistribution = this.selectComponent("#stockdistribution");
    this.deliveryComponent = this.selectComponent("#deliveryComponent");
    //获得配置
    that.getWholesaleConfig();
    if(Number(options.scene) == 1){
      console.log(options.scene,'======options.scene');
      setStorageSync('tabindex',0)
      //导航
      that.loadTemplates();
    }
  },
  /**
   * 判断是否有拍照
   */
  getTakePhotoAuth(){
    //控制是否含有拍照
    let that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    var entity = authorize.getEntity() || authorize.getDefault();
    config.getAuthorityConfig(
      fkflag,
      fkid,
      entity.manager.Token,
      function(res){
        if(res.Success && res.Content){
          let data = res.Content;
          that.checkTakePhoto(data.TakePhoto, data.ProprietorVersion);
        }else{
          that.checkTakePhoto(0, 0);
        }
      },
    );
  },
  checkTakePhoto:function(TakePhoto, ProprietorVersion){
    let that = this;
    let list = that.data.allTabList;
    let tablist = [];
    for (let i = 0; i < list.length; i++) {
      let item = list[i];
      if (item == '拍照') {
        if(TakePhoto == 1){
          tablist.push(item);
        }
      }else if(item == '套餐'){
        //小程序版本ProprietorVersion==1006时不显示套餐
        if (ProprietorVersion != 1006) {
          tablist.push(item);
        }
      }else{
        tablist.push(item);
      }
    }
    that.setData({
      tablist:tablist
    },function(){
      wx.getSystemInfo({
        success: (res)=> {
          that.setData({
            slidewidth: (res.windowWidth / that.data.tablist.length) - 20,
          });
        }
      });
    })
  },

  /**
   * 加载列表 
   * */
  loadList() {
    var that = this;
    let { activeIndex, lists } = this.data;
    let current = lists[activeIndex];
    if (current == null || current == undefined) return;  
    let list_key = "lists[" + activeIndex + "].list";
    let list_has = "lists[" + activeIndex + "].hasMoreData";
    let list_time = "lists[" + activeIndex + "].time";
    let isLoadComplete = "lists[" + activeIndex + "].isLoadComplete";
    //没有登录不显示数据
    if (!authorize.isLogin("store")) {
      that.setData({
        [list_key]:[],
        [isLoadComplete]: true
      });
      return;
    }
    var entity = authorize.getEntity();
    let areaCode = area.getCacheLocation().Code;
    this.data.areaCode = areaCode;
    let param = Object.assign({ areaCode: areaCode}, current.page);
    fastorder.loadList(activeIndex, param, function(content) {
      var hasMoreData = content.count > (current.page.PageIndex) * current.page.PageSize;
      var index = lists[activeIndex].list.length;
      var data = content.data || [];
      for(var i=0;i<data.length;i++){
        data[i].show = false;
        //这里需要把原始值用另一个字段存下来，方便后面计算时用原始值计算
        data[i].SBuyLowerLimit = data[i].BuyLowerLimit || 0;
        data[i].SBuyUpperLimit = data[i].BuyUpperLimit || 0;
        data[i].SStock = data[i].Stock;
        if(that.data.activeIndex != 3 && data[i].IsSingle == 1){
          that.unitList(data[i].AuxiliaryUnits,data[i].UnitPrices,data[i].CartCount,data[i])
        }
      }
      // add a judge by xp
      if (current && current.page) {
        //当分页大于1时，累加
        if (current.page.PageIndex > 1) {
          data = lists[activeIndex].list.concat(data);
        }
      }
      //如果key为变量作为key值的时候要用[]包裹起来
      // console.log(data,'======data=',lists[activeIndex].list);
      that.setData({
        [list_time]:new Date().getTime(),
        [list_key]: data,
        [list_has]: hasMoreData,
        [isLoadComplete]: true
      },function(){
        if (content.data == undefined || activeIndex == 3) return;
        //加载商品活动信息
        activities.loadProductActivities(content.data,false,0,areaCode,function(goodslist, index) {
          var len = lists[activeIndex].list.length;
          for (var i = 0; i < goodslist.length && index + i < len; i++) {
            lists[activeIndex].list[index + i] = goodslist[i];
            goodslist[i].market = Array.from(new Set(goodslist[i].market));
            goodslist[i].Label = Array.from(new Set(goodslist[i].Label));
          }
          for(var i=0;i<goodslist.length;i++){
            goodslist[i].show = false;
            if(goodslist[i].isPanic && goodslist[i].PanicGoods){
              goodslist[i].PanicGoods.map((p)=>{
                that.unitList(goodslist[i].AuxiliaryUnits,p.UnitPrices,goodslist[i].CartCount,goodslist[i])
              })
            }else{
              that.unitList(goodslist[i].AuxiliaryUnits,goodslist[i].UnitPrices,goodslist[i].CartCount,goodslist[i])
            }
          }
          console.log(goodslist,'------===');
          that.setData({
            [list_key]: lists[activeIndex].list,
          });
        }, index);
      });
    });
  },
  unitList(AuxiliaryUnits,UnitPrices,CartCount,goodlist){
    let { quantityDigits } = this.data;
    for(var i=0;i<AuxiliaryUnits.length;i++){
      var item = AuxiliaryUnits[i];
      var t = detail.parseRule(UnitPrices, item.Translated, item.Qty || 0, false);
      if(t.has){
        item.price = t.price;
        if(t.integral){
          item.integral = t.integral;
        }
      }
      var otherAuxiliaryUnits = AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
      var otherUnitQuantity = 0;
      if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
          otherAuxiliaryUnits.map((child, idx) => {
              if (child.Qty!=undefined&&child.Qty>0) {
                  otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
              }
          });
      }
      item.BuyLowerLimit = goodlist.SBuyLowerLimit > 0 && goodlist.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
      item.BuyUpperLimit = goodlist.SBuyUpperLimit > 0 && goodlist.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
      item.Stock = goodlist.SStock > 0 && goodlist.SStock > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SStock - otherUnitQuantity, quantityDigits) : 0;
      item.IsSingle = goodlist.IsSingle;
      item.DefaultUnit = item.Name;
      item.ZeroStockBuy = goodlist.ZeroStockBuy;
      item.SpecValue = goodlist.SpecValue;
      item.ProductId = goodlist.ProductId;
      item.DiscountId = goodlist.DiscountId;
      item.DiscountType = goodlist.DiscountType;
      AuxiliaryUnits[i] = item;
      if(this.data.GoodsUnitDisplayMode == 0&&item.Translated == (goodlist.Translated||goodlist.Radix)){
        goodlist.BuyLowerLimit = item.BuyLowerLimit;
        goodlist.BuyUpperLimit = item.BuyUpperLimit;
        goodlist.Stock = item.Stock;
      }
    }
    // console.log(AuxiliaryUnits,'---=AuxiliaryUnits');
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      (content)=> {
        var fieldDisplayName = content.FieldDisplayName?content.FieldDisplayName.split(','):[];
        var mClassDisplayField = content.MClassDisplayField?content.MClassDisplayField.split('|'):[];
        var classDisplayField = {Price:false,ProductCode:false,PackageSpec:false,BuyLimit:false,BarCode:false,PromotLadder:false,Sell:false};
        for(var i = 0;i<mClassDisplayField.length;i++){
          if (mClassDisplayField[i]=='Sell') {
            classDisplayField[mClassDisplayField[i]]=content.ShowProductSells;
          } else {
            classDisplayField[mClassDisplayField[i]]=true;
          }
        }
        // 快速下单页面为默认样式，不使用新的样式
        let AppQuickTemplateConfig = content.AppQuickTemplateConfig || {TemplateIndex: 0}
        that.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          enableZeroStockBuy: content.EnableZeroStockBuy,
          NotShowProductNoneOffered: content.NotShowProductNoneOffered,  // 是否不显示无货商品按钮
          spectStyle: content.GoodsDisplayMode,
          isScanty: content.IsScanty, //是否允许缺货登记
          decimalDigits: content.DecimalDigits,
          NoLoginShowPrice: content.NoLoginShowPrice,//0：建议零售价 1：不显示价格
          showRetailPrice: content.ShowRetailPrice,
          CartName: api.CartName || '购物车',
          FieldDisplayName: fieldDisplayName,
          ClassDisplayField: classDisplayField,
          IsGoodsTrading: content.IsGoodsTrading,
          GoodsUnitDisplayMode: content.GoodsUnitDisplayMode,
          ShowVendorName: content.ShowVendorName,
          FrontShowStockDetail: content.FrontShowStockDetail,
          AppQuickTemplateConfig: AppQuickTemplateConfig,
          BGColorForMobile: content.BGColorForMobile
        });
        that.productlist.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          enableZeroStockBuy: content.EnableZeroStockBuy,
          NotShowProductNoneOffered: content.NotShowProductNoneOffered,  // 是否不显示无货商品按钮
          showRetailPrice: content.ShowRetailPrice,
          spectStyle: content.GoodsDisplayMode,
          ShowVendorName:content.ShowVendorName,
          addressAssignDepot: content.AddressAssignDepot,
          isScanty: content.IsScanty, //是否允许缺货登记
          NoLoginShowPrice:content.NoLoginShowPrice, //0：建议零售价 1：不显示价格
          BGColorForMobile: content.BGColorForMobile
        });
        var is_search = true;
        //判断前当登录是否是同一个人
        if (this.data.tabKey != "product_" + app.dns.proprietorId + "_" + this.data.fkId) {
          this.data.tabKey = "product_" + app.dns.proprietorId + "_" + this.data.fkId;
          is_search = false;
        }
        if (that.data.activeIndex == 0 || !is_search) {
            that.productlist.setData({
            is_search: is_search
            });
            that.productlist.loadMain();
            if (that.data.activeIndex == 0){
             // that.onWiresharkEven();
              return;
            }

        }
        //如果无需要加载，则更新数量
        if (is_search) {
          that.updateNum();
        }
        else {
          that.cleanList(that);
          that.loadList(false);
        }
        
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //隐藏原生底部导航
    hideTabbar()
    var tabindex = app.getTabBarindex();
    var tabCurrent = getStorageSync('tabcurrent');
    if (app.globalData.pageRefresher.fast) {
      // 登录/退出登录后，重新刷新页面，防止显示上个用户所对应的目录
      app.globalData.pageRefresher.fast = false
      wx.reLaunch({
        url: '/pages/store/purchase/fast/fast'
      })
      return
    }
    that.isCanVisit(()=>{
      let entity = authorize.getEntity();
      let fkId = 0;
      if (app.dns.fkId != app.dns.proprietorId && !entity){
  
      }
      if (entity) {
        fkId = entity.fkId;
      }
      that.data.fkId=fkId;
  
      //获得配置
      that.getTakePhotoAuth();
    })
    if (!authorize.isLogin('store')) {
      tabCurrent = 0;
    }
    that.setData({
      mainColor:api.titleColor||"#e56b14",
      Currency:api.Currency || '￥',
      isLogin:authorize.isLogin('store'),
      tabindex:tabindex,
      cids:app.dns.cid,
      activeIndex:tabCurrent
    });
    const pages = getCurrentPages();
    const length = pages.length;
    const prePage = pages[length - 1]; //上一页
    const page = prePage.__displayReporter.showReferpagepath;
    console.log(page,'009090');
    if(page != 'packageStore/pages/product/detail/detail.html' || page != 'packageStore/pages/purchase/detail/detail.html'){
      that.loadList();
    }
    cart.get_cart_count();
  },
  isCanVisit(callback){
    let that = this;
    this.clearVisitTimer();
    this.data.visitTimer = setTimeout(()=>{
      if(api.isLoginVisit!=undefined){
        that.data.loopCount = 0;
        if ((app.dns.fkFlag != app.dns.proprietor && app.dns.fkId > 0 && app.dns.proprietorId == 0 && !authorize.isLogin('store')) || (api.isLoginVisit&&!authorize.isLogin('store'))) {
          authorize.redirect('store');
        }else{
          callback();
        }
      }else if (that.data.loopCount < 60) {
        that.data.loopCount++;
        that.isCanVisit(callback);
      }
    }, 100)
  },
  clearVisitTimer(){
    if (this.data.visitTimer!=null) {
      clearTimeout(this.data.visitTimer);
      this.data.visitTimer = null;
    }
  },
  /**
   * 更新数量
   */
  updateNum(){
    var that=this;
    var current = this.data.lists[this.data.activeIndex];
    if (current.time && GoodsNumCache.compareTime(current.time)) {
      for (var i = 0; i < current.list.length; i++) {
        current.list[i].CartCount = GoodsNumCache.getProductNum(current.list[i].ProductId, current.list[i].CartCount,current.list[i].IsSingle==1);
      }
      var list_key = "lists[" + that.data.activeIndex + "].list";
      that.setData({
        [list_key]: current.list,
      });
    }
  },
  /**
   * 页面形为抓包
   */
  // onWiresharkEven(){
  //   var current = this.data.lists[this.data.activeIndex];
  //   this.wireshark.setData({
  //     pageKey: current.pageKey
  //   });
  //   this.wireshark.onPageRequst();
  // },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearIncrement();
    this.data.loopCount = 0;
    this.clearVisitTimer();
  },
  /**
   * 移除收藏
   * */
  onRemoveFavorite: function(e) {
    var that = this;
    var current = this.data.lists[this.data.activeIndex];
    
    mall.delFavorite(e.detail.id, function(res) {
      if (res.Success) {
        util.success("取消收藏成功！");
        setTimeout(() => {
          current.page.PageIndex = 1;
          that.loadList();
        }, 1000);

      } else {
        util.tips("取消收藏失败!" + res.Message);
      }

    });
  },
  /**
   * 再次购买 
   * */
  onAginBuyEvent: function(e) {
    var id = e.currentTarget.dataset.orderid;
    var that=this;
    if (that.data.isAginBuying) return;
    that.setData({
      isAginBuying: true
    });
    clickIncrement(function(){
      fastorder.aginBuy(id,function(){
        that.setData({
          isAginBuying: false
        });
      });
    });
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.activeIndex == 4) return;
    this.setData({
      listType:false
    })
    wx.stopPullDownRefresh();
    if (this.data.activeIndex == 0) {
      this.productlist.onPullDownRefresh();
      return;
    }

    this.data.lists[this.data.activeIndex].page.PageIndex = 1;
    this.data.lists[this.data.activeIndex].list = [];
    this.loadList();
    
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function(e) {
    if (this.data.activeIndex == 0) {
      this.productlist.onReachBottom(e);
      return;
    }
    var current = this.data.lists[this.data.activeIndex];
    if (current.hasMoreData) {
      var index = this.data.lists[this.data.activeIndex].page.PageIndex;
      this.data.lists[this.data.activeIndex].page.PageIndex = index + 1;
      this.loadList();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let path = pagesInfo.category.url + `?scene=1`; 
    return { 
      path: path 
    }
  },
  /**
   * 切换选项
   */
  swichNav: function(res) {
    var activeIndex = res.detail.currentNum.id;
    if (activeIndex > 0 && !this.data.isLogin) {
      util.tips("请先登录");
      authorize.redirect("store");
      return;
    }
    if (this.data.activeIndex == activeIndex) return;
    if(activeIndex == 4){
      wx.navigateTo({
        url: '/pages/store/purchase/setmealList/index',
      })
      return;
    }
    this.setData({
      sliderOffset: res.detail.currentNum.offsetLeft,
      activeIndex: activeIndex
    });
    // console.log(activeIndex,'=====activeIndex');
    setStorageSync('tabcurrent',activeIndex)
    if (activeIndex == 0) {
      this.productlist.setData({
        is_search: true
      });
      this.productlist.loadMain();
      return;
    }
    
    if (activeIndex == 5) return;
    this.deliveryComponent.getDefaultAddress();
    var current = this.data.lists[activeIndex];
    let obj = area.getCacheLocation();
    if (obj && Object.keys(obj).length > 0 && obj.Code != this.data.areaCode) {
      current.PageIndex=1;
      this.cleanList(this);
      this.loadList();
    }
    else if (current != undefined && (current.list == null || current.list.length == 0)) {
      this.loadList();
    }
    else{
      this.updateNum();
    }
  },
  /**
   * 输入事件
   */
  onInputEvent: function(e) {
    this.data.code = e.detail.value;
  },
  /**
   * 扫码
   */
  onScanCodeEvent: function(e) {
    var that = this;
    // 只允许从相机扫码
    wx.scanCode({
      //onlyFromCamera: true,
      success: (res) => {
        //that.data.code = res.result;
        console.log(res.result,'=====code')
        that.setData({
          code: res.result
        });
        that.onSearchProductCodeEvent(e);
      }
    })
  },
  /**
   * 根据code搜索商品
   */
  onSearchProductCodeEvent: function(e) {
    var that = this;
    if (!authorize.isLogin("store")) {
      util.tips("请先登录");
      authorize.redirect("store");
      return;
    }
    if (that.data.code.length == 0) {
      util.alert("请输入商品编码");
      return;
    }
    that.fasterComponent.setData({
      item: null,
      addCompleted:null,
      code: that.data.code,
      quantityDigits: that.data.quantityDigits,
      priceDigits: that.data.priceDigits,
      isScanty: that.data.isScanty,
      areaCode: that.data.addr!=undefined?that.data.addr.code:''
    });
    that.fasterComponent.onSearchProductCode(e);
  },
  /**
   * 表单值绑定
   */
  bindFormValue: function(e) {
    e = e.detail;
    this.data[e.target.id] = e.detail.value;

  },
  /*
   弹出缺货登记的层 
   */
  onShowScanty(e) {
    var that = this;
    var idx = e.detail.idx;
    var activeIndex = this.data.activeIndex;
    var product = this.data.lists[activeIndex].list[idx];
    if (product.IsSingle == 0) {
      that.onShowGoodsModal({ detail: { product: product, idx: idx } });
    } else {
      let unit_index = 0;
      for (let k = 0; k < product.AuxiliaryUnits.length; k++) {
        if (product.AuxiliaryUnits[k].Name == product.AuxUnit) {
          unit_index = k;
          break;
        }
      }
      product.ZIndex = unit_index;
      if(product.EnableSKUTranslated!=1){
        let units = product.AuxiliaryUnits||[];
        product.productUnitText = detail.loadUnitContext(units, product.Unit);
      }
      console.log(product,'========scantyProduct')
      that.outofstock.setData({
        scantyProduct: product,
      })
      that.outofstock.openScanyDialog(e);
    }
  },
  
  showStockDistribution(e) {
    var idx = e.detail.idx;
    var activeIndex = this.data.activeIndex;
    var product = this.data.lists[activeIndex].list[idx];
    this.stockdistribution.setData({
      product: product,
    })
    this.stockdistribution.showStockModal(e);
  },

  /**
   * 隐藏遮罩层
   */
  hideModal: function() {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
   * 清除每一列
   */
  cleanList: function(that) {
    for (var i = 0; i < that.data.lists.length-1; i++) {
      if(that.data.lists[i].list){
        that.data.lists[i].list = [];
        that.data.lists[i].page.PageIndex = 1;
      }
    }
    that.setData({
      lists: that.data.lists
    });
  },
  onPageScroll: function (e) {
    if (!this.productlist) return;
    if (this.scroll_timeout) {
      clearTimeout(this.scroll_timeout);
    }
    let scrollTop = e.scrollTop;
    this.scroll_timeout = setTimeout(()=>{
      this.productlist.setScollTop(scrollTop)
    }, 50);
  },
  /**
   * 页面滚动到
   */
  onPageScrollTo(e){
    wx.pageScrollTo({
      scrollTop: e.detail.scrollTop,
      duration: 0
    })  
  },
  /**
 * 加入完成后调用，更新界面显示数量
 */
  onAddCartCompleted(e) {
    e = e.detail;
    var activeIndex = this.data.activeIndex;
    let key = "lists[" + activeIndex+"].list[" + e.idx + "]";
    this.setData({
      [key]: e.product
    });
  },
  /**显示多规则 */
  onShowGoodsModal(e) {
    // console.log(e,'====');
    var that = this;
    e = e.detail;
    var activeIndex = this.data.activeIndex;
    let { addr, priceDigits, quantityDigits, isScanty } = this.data;
    let product = this.data.lists[activeIndex].list[e.idx];
    that.fasterComponent.setData({
      item: product,
      isScanty: isScanty,
      quantityDigits: quantityDigits,
      priceDigits: priceDigits,
      areaCode: addr?addr.code:'',
      addCompleted: function (goods) {
        that.onAddCartCompleted({ detail: { product: goods, idx: e.idx } });
      }
    });
    that.fasterComponent.onShowGoodsModal(e);
  },
  bindUnfold(e){
    var activeIndex = this.data.activeIndex;
    let product = this.data.lists[activeIndex].list[e.detail.idx];
    product.show = !product.show;
    this.setData({
      lists: this.data.lists
    })
  },
  /**
   * 进入详情
   */
  toDetail(e){
    e = e.detail;
    theme.routerTo(e.url, e.linkparam);
  },
  /**
   * 收货地址
   */
  showDelivery(e) {
    this.deliveryComponent.loadAdressList(e);
  },
  /**
   * 选择地址后回调
   */
  onSelectedAdressCallBack(e) {
    this.setData({
      addr: { area: e.detail.Area, code: e.detail.Code }
    })
  },
  completeCallBack() {
    //获取购物车数量
    cart.get_cart_count();
    //页面形为抓包
    //this.onWiresharkEven();
  },
  /**
   * 上传图片
   */
  bindUploadPhoto:function(){
    var that = this;
    if (this.data.photolist.length >= 9) {
      util.tips("最多只能上传9张");
      return;
    }
    var count = 9 - this.data.photolist.length;
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        tempFilePaths.map(function (item) {
          that.data.photolist.push(item);
        })
        that.setData({
          photolist: that.data.photolist
        });
        var data = {num:3001,type:3,tempFilePaths:tempFilePaths};
        upload.upload_image_server(data, function (image_list) {
          if (image_list.length==0){
            util.alert("上传失败");
            return;
          }
          image_list.map(function (item) {
            that.data.virtualImageList.push(item);
          });
        })
      }
    });
  },
  /**
   * 删除照片
   */
  onDelPhotoEvent:function(e){
    let n = e.currentTarget.dataset.imgidx;
    let {photolist,virtualImageList} = this.data;
    photolist.splice(n,1);
    virtualImageList.splice(n,1);
    this.setData({
      photolist,
      virtualImageList
    })
  },
  /**
   * 提交拍照下单
   */
  bindPhotoSubmit:function(){
    let that = this;
    order.photoOrderSubmit(that.data.virtualImageList,function(res){
      if(res.Success){
        util.success("提交订单成功");
        router.navigate({
          path:'photoSuccess'
        });
        that.setData({
          photolist:[],
          virtualImageList:[]
        })
      }else{
        util.tips("提交订单失败!" + res.Message);
      }
    })  
  },
  //自定义导航跳转到相应界面
  bindCurrent(e){
    var tabindex = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    var cid = e.currentTarget.dataset.cid;
    var fastId = e.currentTarget.dataset.fast;
    this.setData({ cids:Number(cid) });
    if(cid){
      this.onPullDownRefresh()
    }
    if(fastId){
      this.setData({ activeIndex:fastId });
    }
    // if (type == 1) {
    //   this.setData({ tabindex: tabindex });
    // }
    app.onChangeTabBar(e);
  },
  
  loadTemplates(){
    let that = this;
    let entity = authorize.getEntity() || authorize.getDefault();
    theme.loadPageWidgetsName(entity.fkId, (copy_result)=>{
      var str = copy_result[0].Keyword + "|" + copy_result[0].WidgetName;
      that.setData({
        widgets:copy_result
      })
      that.initPageWidgets(str,copy_result)
    }); 
  },
  initPageWidgets(wStrs,copy_result,callback) {
    var that = this;
    var entity = authorize.getEntity();
    var param = {
      FKFlag: app.dns.proprietor,
      FKWay: app.dns.fkWay,
      UserId: entity != undefined ? entity.fkId : 0, // 登录用户Id,
      Sid: app.dns.proprietorId, //网页所有者Id,
      ProprietorId: app.dns.proprietorId,
      Widgets: wStrs,
      AreaId: ''
    };
    // var widgets = that.data.widgets;
    util.post("theme.data.getpagewidgetdbdata", param,(res)=> {
      var data = res.data;
      if (data.Success) {
        // theme.getFootBar(copy_result);
        that.decorateWidgets(copy_result, 0, data, callback);
      }
    }, '3.0', null, false);
  },
  decorateWidgets(wlist, _wlist_index, data, callback) {
    let that=this;
    let { widgets}=that.data;
    let wdatalist = data.Content;

    if (Object.keys(wdatalist).length <= 0) {
      return
    };
    //组装数据
    for (var i = 0; i < wlist.length; i++) {
      let index = _wlist_index + i;
      let w = widgets[index];
      let keyword = w.Keyword;
      let wd = wdatalist[keyword];
      if (wd && wd.length > 0) {
        w.Datas = wd;
      }
    }
    that.setData({
      widgets: widgets
    }, function () {
      if (callback && typeof (callback) == "function") {
        callback();
      };
      setTimeout(function(){
        theme.getFootBar(widgets);
      },500)
    });
  },
})